package com.wl.shixun3.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤器 - 拦截所有需要登录才能访问的页面
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = {"/shixun3/success.jsp", "/shixun3/changePassword.jsp"})
public class LoginFilter implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 获取请求的URI
        String uri = httpRequest.getRequestURI();
        
        // 获取session
        HttpSession session = httpRequest.getSession(false);
        
        // 允许访问的路径（登录、注册、忘记密码等）
        String contextPath = httpRequest.getContextPath();
        
        // 允许访问的资源路径
        if (uri.contains("/css/") || uri.contains("/js/") || uri.contains("/images/")) {
            chain.doFilter(request, response);
            return;
        }
        
        // 允许访问的Servlet和JSP路径
        String[] allowedPaths = {
            contextPath + "/shixun3/login",
            contextPath + "/shixun3/login.jsp",
            contextPath + "/shixun3/register",
            contextPath + "/shixun3/register.jsp",
            contextPath + "/shixun3/registerSuccess.jsp",
            contextPath + "/shixun3/forgotPassword",
            contextPath + "/shixun3/forgotPassword.jsp",
            contextPath + "/shixun3/resetSuccess.jsp"
        };
        
        // 检查是否是允许访问的路径
        for (String allowedPath : allowedPaths) {
            if (uri.equals(allowedPath)) {
                chain.doFilter(request, response);
                return;
            }
        }
        
        // 检查用户是否已登录（检查三个条件：session存在、user对象存在、认证标记存在）
        if (session == null || 
            session.getAttribute("user") == null || 
            session.getAttribute("isAuthenticated") == null ||
            !Boolean.TRUE.equals(session.getAttribute("isAuthenticated"))) {
            // 未登录，重定向到登录页面
            httpResponse.sendRedirect(contextPath + "/shixun3/login.jsp?error=notLoggedIn");
            return;
        }
        
        // 已登录，允许访问
        chain.doFilter(request, response);
    }
    
    @Override
    public void destroy() {
        // 清理资源
    }
}

